<?php

namespace App\Console\Commands;

use App\Http\Logic\MerchantLogic;
use App\Models\SwtBjAsyncOrder;
use App\Models\SwtMachine;
use App\Models\SwtOrder;
use App\Services\BaoJianOrderService;
use Illuminate\Console\Command;

class AsyncBjOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'async_bj_order:worker';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步宝坚设备订单';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        //获取付款订单
        $this -> getPayOrder();
        //获取退款订单
        $this -> getRefundOrder();
        //订单分润
        $this -> orderProfit();
    }


    public function getPayOrder() {
        $res = SwtBjAsyncOrder::orderBy('pay_time','desc') -> first();

        $params['beginPayTime'] = $res ? $res['pay_time'] : date('Y-m-d H:i:s', strtotime('-1 month', time()));

        $params['endPayTime'] = date('Y-m-d H:i:s', time());

        $order_list = BaoJianOrderService::getOrderList($params);

        if(empty($order_list)){
            return;
        }

        $add = 0;

        foreach($order_list as $order) {
            $info = SwtBjAsyncOrder::where('order_id', $order['orderId'])->first();
            if($info) {
                continue;
            }

            $data = [
                'order_id'     => $order['orderId'],
                'device_code'  => $order['deviceCode'],
                'device_name'  => $order['deviceName'],
                'cabinet_no'   => $order['cabinetNo'],
                'order_status' => $order['orderStatus'],
                'phone_number' => $order['phoneNumber'],
                'pay_mode'     => $order['payMode'],
                'order_time'   => $order['orderTime'],
                'pay_time'     => $order['payTime'],
                'pay_sn'       => $order['paySn'],
                'order_total'  => $order['receivableAmount'],
                'pay_total'    => $order['receiveAmount'],
                'created_at'   => date('Y-m-d H:i:s', time())
            ];

            $res = SwtBjAsyncOrder::create($data);

            $res && $add ++ ;
        }

        echo '新增付款订单'.$add.'条';
    }

    public function getRefundOrder()
    {
        $res = SwtBjAsyncOrder::orderBy('refund_time','desc') -> first();

        $params['beginRefundTime'] = $res ? $res['refund_time'] : date('Y-m-d H:i:s', strtotime('-1 month', time()));

        $params['endRefundTime'] = date('Y-m-d H:i:s', time());

        $order_list = BaoJianOrderService::getRefundOrderList($params);

        if(empty($order_list)){
            return;
        }

        $update = 0;

        foreach($order_list as $order) {
            $info = SwtBjAsyncOrder::where('order_id',$order['orderId']) -> first();
            if(!$info) {
                continue;
            }
            $data = [
                'order_status' => 6,
                'refund_id'    => $order['refundId'],
                'refund_total' => $order['refundAmount'],
                'refund_time'  => $order['refundTime'],
                'is_async'     => 0
            ];
            $res = $info -> update($data);

            $res && $update++;
        }

        echo '修改退款订单'.$update.'条';
    }

    public function orderProfit()
    {
        $order_list = SwtBjAsyncOrder::with(['machine','order']) -> where('is_async', 0) -> whereIn('order_status',[3,6]) -> get();

        if(empty($order_list)){
            return;
        }

        $order_list = $order_list -> toArray();

        foreach($order_list as $order) {

            if(!$order['machine']) {
                SwtBjAsyncOrder::where('id', $order['id']) -> update(['is_async' => 2, 'async_desc' => '设备未找到']);
                continue;
            }

            $order_data = [
                'user_id'           => 2,
                'machine_id'        => $order['machine']['id'],
                'door_num'          => $order['cabinet_no'],
                'pay_type'          => 0,
                'platform'          => 'wechat',
                'transaction_id'    => $order['pay_sn'],
                'state'             => 'DONE',
                'order_amount'      => $order['order_total'] * 100,
                'refund_amount'     => $order['refund_total'] * 100,
                'pay_amount'        => $order['pay_total'] * 100,
                'state_description' => 'MCH_COMPLETE',
                'is_pay'            => 1,
                'is_refund'         => $order['order_status'] == 6 ? 1 : 0,
                'is_notify'         => 1,
                'is_warning'        => 0,
                'payment_at'        => $order['pay_time'],
                'refund_at'         => $order['refund_time']
            ];

            $res = SwtOrder::updateOrCreate(['order_sn' => $order['order_id']], $order_data);

            if(!$res) {
                SwtBjAsyncOrder::where('id', $order['id']) -> update(['is_async' => 2, 'async_desc' => '订单存储失败']);
                continue;
            }

            $order_id = $res -> id;

            SwtBjAsyncOrder::where('id', $order['id']) -> update(['is_async' => 1, 'async_desc' => null]);
            //修改设备销量
            if($order['order_status'] == 3) {
                SwtMachine::where('id', $order['machine']['id']) -> increment('total_amount', $order['pay_total'] * 100);
                MerchantLogic::setMerchantProfit($order['machine']['id'], $order['pay_total'] * 100, $order_id, $order['order_id']);
            }

            if($order['order_status'] == 6 && $order['order'] && $order['order']['is_refund'] == 0) {
                SwtMachine::where('id', $order['machine']['id']) -> decrement('total_amount', $order['refund_total'] * 100);
                MerchantLogic::setMerchantProfit($order['machine']['id'], $order['refund_total'] * 100, $order_id, $order['order_id']);
            }
        }
    }
}
